package com.yaorange.store.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


//根据请求的参数调用不同的方法


public class BaseServlet extends HttpServlet {
    /**
     * 通过method参数调用(反射)不同的处理方法
     * 反射：不知道调用什么方法
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取method参数
        String methodName = req.getParameter("method");

        //2.获取到需要调用的对象
        Class<? extends BaseServlet> aClass = this.getClass();

        //3.通过反射调用方法
        try {
            Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            String view = (String) method.invoke(this, req, resp); //invoke自己

            //请求转发
            req.getRequestDispatcher("/"+view+".jsp").forward(req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
